import React from "react";
class ErrorBoundary extends React.Component {
    constructor(props) {
        super(props)
        this.state = { error: null, errInfo: null }
    }

    static getDerivedStateFromError(error){
        // 这里是知道发生了错误
        console.log(error)
    }

    componentDidCatch(err, errInfo) {
         // 这里可以获取具体的错误信息
        this.setState({ error: err, errInfo: errInfo })
    }

    render() {
        if (this.state.error) {
            return <div>error:{this.state.error.toString()}
            stack:{this.state.errInfo.componentStack}
            </div>
        }

        return this.props.children
    }
}

class BugProducer extends React.Component {
    constructor(props) {
        super(props)
        this.state = { count: 0 }
    }

    increment() {
        const count = this.state.count
        this.setState({ count: count + 1 })
    }

    render() {
        if (this.state.count == 3)
            throw new Error('i crashed')

        return <button onClick={() => this.increment()}>Increment{this.state.count}</button>
    }
}

export default function ErrorBoundaries(props) {
    return <div><ErrorBoundary>
        <BugProducer />
    </ErrorBoundary>
    </div>
}